// 云函数入口文件
const cloud = require('wx-server-sdk')
const https = require('https')
const http = require('http')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const imagesCollection = db.collection('images')
const usersCollection = db.collection('users')

// 确保数据库集合存在
async function ensureCollectionExists(collectionName) {
  try {
    // 检查集合是否存在
    const collections = await db.collections()
    const collectionNames = collections.data.map(col => col.name)
    
    if (!collectionNames.includes(collectionName)) {
      console.log(`集合 ${collectionName} 不存在，正在创建...`)
      await db.createCollection(collectionName)
      console.log(`集合 ${collectionName} 创建成功`)
    } else {
      console.log(`集合 ${collectionName} 已存在`)
    }
    return true
  } catch (error) {
    console.error(`确保集合 ${collectionName} 存在时出错:`, error)
    return false
  }
}

// 从URL直接下载图片
function downloadImageFromUrl(url) {
  return new Promise((resolve, reject) => {
    console.log('直接从URL下载图片:', url);
    
    // 选择http或https
    const client = url.startsWith('https') ? https : http;
    
    client.get(url, (response) => {
      // 检查状态码
      if (response.statusCode < 200 || response.statusCode > 299) {
        reject(new Error(`下载图片失败: HTTP Status Code ${response.statusCode}`));
        return;
      }
      
      // 收集数据
      const chunks = [];
      response.on('data', (chunk) => chunks.push(chunk));
      response.on('end', () => {
        const buffer = Buffer.concat(chunks);
        console.log('图片下载完成，大小:', buffer.length, '字节');
        resolve(buffer);
      });
    }).on('error', (err) => {
      console.error('下载图片错误:', err);
      reject(err);
    });
  });
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openId = wxContext.OPENID
  
  if (!openId) {
    return {
      success: false,
      message: '未获取到用户OpenID'
    }
  }
  
  // 确保集合存在
  await ensureCollectionExists('images')
  
  const { imageUrl, prompt, taskId } = event
  
  if (!imageUrl || !prompt) {
    return {
      success: false,
      message: '缺少必要参数'
    }
  }
  
  try {
    // 1. 获取用户信息
    const userRes = await usersCollection.where({ openId }).get()
    if (!userRes.data || userRes.data.length === 0) {
      return {
        success: false,
        message: '用户不存在'
      }
    }
    
    const user = userRes.data[0]
    const userId = user._id
    
    // 2. 获取图片内容
    let fileContent;
    
    console.log('处理图片URL:', imageUrl);
    
    try {
      // 尝试直接从URL下载图片
      if (imageUrl.startsWith('http')) {
        fileContent = await downloadImageFromUrl(imageUrl);
      } else if (imageUrl.startsWith('cloud://')) {
        // 处理云存储文件ID
        const result = await cloud.downloadFile({
          fileID: imageUrl
        });
        fileContent = result.fileContent;
      } else {
        throw new Error('不支持的图片URL格式');
      }
    } catch (dlErr) {
      console.error('下载图片失败:', dlErr);
      return {
        success: false,
        message: '下载图片失败',
        error: dlErr.toString()
      };
    }
    
    if (!fileContent || fileContent.length === 0) {
      return {
        success: false,
        message: '无法获取图片内容或内容为空'
      };
    }
    
    // 3. 上传到云存储
    const timestamp = Date.now()
    const cloudPath = `ai-images/${userId}_${timestamp}.jpg`
    
    console.log('准备上传图片到云存储:', cloudPath);
    
    const uploadResult = await cloud.uploadFile({
      cloudPath,
      fileContent
    })
    
    const fileID = uploadResult.fileID
    console.log('图片上传成功，fileID:', fileID);
    
    // 4. 保存到数据库
    const addResult = await imagesCollection.add({
      data: {
        prompt,
        originalImageUrl: imageUrl,
        imageUrl: fileID,
        userId,
        taskId,
        openId,
        createdAt: db.serverDate(),
        likes: 0,
        isPublic: true
      }
    })
    
    // 5. 更新用户的图片计数
    await usersCollection.doc(userId).update({
      data: {
        imageCount: db.command.inc(1),
        updateTime: db.serverDate()
      }
    })
    
    return {
      success: true,
      imageId: addResult._id,
      fileID,
      prompt,
      userInfo: {
        nickName: user.nickName,
        avatarUrl: user.avatarUrl
      }
    }
    
  } catch (err) {
    console.error('发布图片失败', err)
    return {
      success: false,
      message: '发布图片失败',
      error: err.toString()
    }
  }
} 